package com.hqd.test.event;

import com.hqd.ch03.v14.utils.GenericClassUtils;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class GieGieEventPublisher {
    private Set<GieGieListener> listeners = new LinkedHashSet<>();

    /**
     * 发布事件
     *
     * @param event
     */
    public void publishEvent(GieGieEvent event) {
        List<GieGieListener> fans = getFans(event);
        for (GieGieListener listener : fans) {
            listener.doSomething(event);
        }
    }

    private List<GieGieListener> getFans(GieGieEvent event) {
        Class eventClass = event.getClass();
        List<GieGieListener> fans = new ArrayList<>(listeners.size());
        for (GieGieListener listener : listeners) {
            //查找接口泛型
            Class<?> typeArgument = GenericClassUtils
                    .getInterfaceActualTypeArgument(listener.getClass(), GieGieListener.class, 0);
            if (typeArgument.isAssignableFrom(eventClass)) {
                fans.add(listener);
            }
        }
        return fans;

    }

    public void addListener(GieGieListener listener) {
        listeners.add(listener);
    }

    public void removeListener(GieGieListener listener) {
        listeners.remove(listener);
    }
}
